using System.ComponentModel;

namespace 后台工作
{
    public partial class Form1 : Form
    {
        BackgroundWorker bw = new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
            bw.DoWork += new DoWorkEventHandler(DoWork);
            progressBar1.Maximum = 100;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (bw.IsBusy)
            {
                return;
            }
            else
            {
                bw.RunWorkerAsync();
            }
        }

        /// <summary>
        /// 这里是真正的后台工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DoWork(Object sender, DoWorkEventArgs args)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            int num = 101;
            for (int i = 0; i < num; i++)
            {
                if (bw.CancellationPending)
                {
                    bw.ReportProgress(i, $"当前进度{i}%, 已停止！");
                    return;
                }

                // 通知进度变化
                bw.ReportProgress(i, $"当前进度{i}%");
                Thread.Sleep(100);
            }
            return;
        }

        /// <summary>
        /// 后台工作进度变化调用这里
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProgressChanged(Object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label1.Text = e.UserState.ToString();
            label1.Update();
        }

        /// <summary>
        /// 后台工作完成调用这里
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("后台操作执行完成！");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bw.CancelAsync();
        }
    }
}
